/*
 *
 *  Copyright (C) 2012-2024
 *  All rights reserved, Designed By 杭州连线客信息技术有限公司
 *  注意：
 *  本软件为杭州连线客信息技术有限公司开发研制，未经购买不得使用
 *  购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 *  一经发现盗用、分享等行为，将追究法律责任，后果自负
 *
 */

package com.lxk.oms.flow.pay;

import com.lxk.oms.order.domain.vo.OmsOrderItemVo;
import com.lxk.oms.order.service.IOmsOrderItemService;
import com.lxk.service.core.Result;
import com.lxk.service.pms.api.PmsServiceApi;
import com.lxk.service.pms.request.ProductSkuUpdateStockParam;
import com.lxk.service.pms.response.SkuUpdateStockResult;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import lombok.AllArgsConstructor;
import org.dromara.common.core.exception.ServiceException;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 确认库存操作
 *
 * @author huahua
 * 2024/8/28
 */
@LiteflowComponent(value = FlowPayOrderNodeConst.ACT_STOCK_NODE)
@AllArgsConstructor
public class ReducePmsStockNode extends NodeComponent {
    private final IOmsOrderItemService omsOrderItemService;
    private final PmsServiceApi serviceApi;

    @Override
    public void process() throws Exception {

        PayContext contextBean = getContextBean(PayContext.class);
        contextBean.getOmsOrder().forEach(order -> {
            Boolean needStock = contextBean.needStock(order);
            // 是否需要扣减库存
            if (needStock) {
                Long id = order.getId();
                Result<SkuUpdateStockResult> result = serviceApi.actCutSkuStock(buildParam(id));
                if (result.isFail()) {
                    throw new ServiceException(result.getMsg());
                }
                if (!result.getData().getResult()) {
                    throw new ServiceException(result.getData().getMessage());
                }
            }
        });


    }

    private ProductSkuUpdateStockParam buildParam(Long orderId) {
        // 预扣库存确认扣除
        List<OmsOrderItemVo> orderItemVoList = omsOrderItemService.queryByOrderIdList(orderId);
        ProductSkuUpdateStockParam param = new ProductSkuUpdateStockParam();
        List<ProductSkuUpdateStockParam.Item> itemList = orderItemVoList.stream().map(item -> {
            Long skuId = item.getSkuId();
            Integer count = item.getCount();
            return new ProductSkuUpdateStockParam.Item(skuId, count, "");
        }).collect(Collectors.toList());
        param.setItems(itemList);
        return param;
    }

    @Override
    public boolean isAccess() {
        PayContext contextBean = getContextBean(PayContext.class);
        return contextBean.isNotThirdPay() && contextBean.isPay();
    }
}
